package com.wjjun.basemvpvm.databinding.adapter;

import android.databinding.BindingAdapter;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.request.RequestOptions;

import java.io.File;

/**
 * author Wjjun
 * Created 2018/3/14.
 */

public class ImageViewAdapter {

    private static String baseUrl;

    public static String getBaseUrl() {
        return baseUrl;
    }

    public static void setBaseUrl(String url) {
        baseUrl = url;
    }

    public static String getPicUrl(String url) {
        return baseUrl + url;
    }


    @BindingAdapter(value = {"url", "defImg", "isCircle", "defRes"}, requireAll = false)
    public static void image(ImageView imageView, String url, Drawable defImg, boolean isCircle, int defRes) {
        if (!TextUtils.isEmpty(url) && !url.trim().isEmpty()) {
            RequestOptions options;
            if (isCircle) {
                options = RequestOptions.circleCropTransform();
            } else {
                options = new RequestOptions();
            }
            if (defRes != 0) {
                options = options.format(DecodeFormat.PREFER_RGB_565).error(defRes).placeholder(defRes);
            } else if (defImg != null) {
                options = options.format(DecodeFormat.PREFER_RGB_565).error(defImg).placeholder(defImg);
            }
            if (url.startsWith("/storage") || url.contains("/emulated/")) {  //本地图片
                Glide.with(imageView.getContext()).load(new File(url)).apply(options).
                        into(imageView);
            } else if (url.startsWith("http")) {  //完整地址
                Glide.with(imageView.getContext()).load(url).apply(options).
                        into(imageView);
            } else if (!TextUtils.isEmpty(getBaseUrl())) {  //基础地址不为空,则拼接
                Glide.with(imageView.getContext()).load(getPicUrl(url)).apply(options).
                        into(imageView);
            }
        } else {
            if (defRes != 0) {
                imageView.setImageResource(defRes);
            } else if (defImg != null) {
                imageView.setImageDrawable(defImg);
            }
        }
    }

    @BindingAdapter(value = "android:src")
    public static void setImage(ImageView imageView, int resId) {
        if (resId != 0) {
            imageView.setImageResource(resId);
        }
    }
}
